import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../../services/settings_service.dart';

class CustomTestDialog extends StatefulWidget {
  const CustomTestDialog({super.key});

  static void show(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,      
      transitionAnimationController: AnimationController(
        duration: const Duration(milliseconds: 300),  // 设置动画时长
        vsync: Navigator.of(context),
      ),
      builder: (context) => const CustomTestDialog(),
    );
  }

  @override
  State<CustomTestDialog> createState() => _CustomTestDialogState();
}

class _CustomTestDialogState extends State<CustomTestDialog> {
  String _selectedMode = '做题模式';  // 默认模式
  int _selectedModeValue = 0;        // 添加这行用于存储
  int _selectedNumber = 10;  // 默认数量
  final List<int> _numbers = [5, 10, 15, 20, 25, 30, 35, 40];
  late FixedExtentScrollController _scrollController;  // 添加控制器

  @override
  void initState() {
    super.initState();
    // 先创建控制器
    _scrollController = FixedExtentScrollController(
      initialItem: _numbers.indexOf(_selectedNumber),
    );
    _loadSettings();
  }

  @override
  void dispose() {
    _scrollController.dispose();  // 释放控制器
    super.dispose();
  }

  Future<void> _loadSettings() async {
    final mode = await SettingsService.getExamMode();
    final count = await SettingsService.getQuestionCount();
    
    setState(() {
      _selectedModeValue = mode;
      _selectedMode = mode == 0 ? '做题模式' : '背题模式';      
      _selectedNumber = count;
    });
    
    // 加载完设置后，跳转到正确的位置
    _scrollController.jumpToItem(_numbers.indexOf(_selectedNumber));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              const Text(
                '自定义刷题',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              // 副标题
              Text(
                '上次未完成的题组不受此设置影响',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 24),
              
              // 模式选择
              const Text(
                '出题模式',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 12),
              Row(
                children: [
                  _buildModeButton('做题模式'),
                  const SizedBox(width: 12),
                  _buildModeButton('背题模式'),
                ],
              ),
              const SizedBox(height: 24),
              
              // 数量选择
              const Text(
                '每组题目数量',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 12),
              SizedBox(
                height: 150,
                child: CupertinoPicker(
                  scrollController: _scrollController,  // 使用成员变量
                  itemExtent: 40,
                  onSelectedItemChanged: (index) {
                    setState(() {
                      _selectedNumber = _numbers[index];
                    });
                  },
                  children: _numbers
                      .map((number) => Center(
                            child: Text(
                              number.toString(),
                              style: const TextStyle(fontSize: 20),
                            ),
                          ))
                      .toList(),
                ),
              ),
              
              // 确认按钮
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () async {
                    // 保存设置
                    await SettingsService.saveExamMode(_selectedModeValue);
                    await SettingsService.saveQuestionCount(_selectedNumber);
                    
                    if (context.mounted) {
                      Navigator.pop(context, {
                        'mode': _selectedModeValue,
                        'count': _selectedNumber,
                      });
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF4B6BFB),
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '确认',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildModeButton(String mode) {
    final isSelected = _selectedMode == mode;
    return Expanded(
      child: GestureDetector(
        onTap: () {
          setState(() {
            _selectedMode = mode;
            _selectedModeValue = mode == '做题模式' ? 0 : 1;  // 添加这行
          });
        },
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFF4B6BFB) : Colors.grey[100],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: Text(
              mode,
              style: TextStyle(
                color: isSelected ? Colors.white : Colors.black87,
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ),
    );
  }
}